//
//  MenuView.swift
//  ios_swift_demo1
//
//  Created by liutao on 2020/7/23.
//  Copyright © 2020 lt. All rights reserved.
//
//import UIKit


import UIKit

protocol SwiftPopMenuDelegate :NSObjectProtocol{
    func swiftPopMenuDidSelectIndex(index:Int)
}

protocol SwiftPopMenuStateDelegate :NSObjectProtocol{
    func swiftPopMenuState(iShow:Bool)
}


public class SwiftPopMenu: UIView {
    
    //delegate
    weak var delegate : SwiftPopMenuDelegate?
    
    weak var stateDelega : SwiftPopMenuStateDelegate?
    
    //block
    public var didSelectMenuBlock:((_ index:Int)->Void)?
    
    
    //／*  -----------------------  外部参数 通过configure设置 ---------------------------- *／

    //圆角弧度
    private var popMenuCornorRadius:CGFloat = 6

    //菜单高度
    private var popMenuItemHeight:CGFloat = 44.0

    //菜单与屏幕边距
    private var popMenuMargin:CGFloat = 10
    
    //／*  -----------------------  外部参数 over------------------------------------------ *／
    
    private var arrowPoint : CGPoint = CGPoint.zero         //小箭头位置
    private var arrowViewWidth : CGFloat = 15               //三角箭头宽
    private var arrowViewHeight : CGFloat = 10               //三角箭头高
    private var popData:[(String)]!       //数据源
    
    static let cellID:String = "SwiftPopMenuCellID"
    private var myFrame:CGRect!     //tableview  frame
    private var arrowView : UIView! = nil
    
    var tableView:UITableView! = nil
    

    
 ///   初始化菜单
 ///
 /// - Parameters:
 ///   - menuWidth: 菜单宽度
 ///   - arrow: 箭头位置是popmenu相对整个屏幕的位置
 ///   - datas: 数据源，icon允许传空，数据源没数据，不会显示菜单
 ///   - configure: 配置信息，可不传
    init(menuWidth:CGFloat,arrow:CGPoint,datas:[(String)] = []) {
        super.init(frame: UIScreen.main.bounds)
        self.frame = UIScreen.main.bounds
        popData = datas
        //设置myFrame size  ,original会在后面计算
        myFrame = CGRect(x: 0, y: 0, width: menuWidth, height: popMenuItemHeight*CGFloat(popData.count))
        myFrame.size.height = (203/667)*screenHeight
        myFrame.size.width = min(screenWidth-popMenuMargin*2, myFrame.width)
        //设置肩头，与屏幕间隔10
        arrowPoint = arrow
        arrowPoint.x = max(popMenuMargin, min(arrowPoint.x, screenWidth-popMenuMargin))
    }
    
    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    func initViews() {
        
        let arrowPs = getArrowPoints()
        myFrame.origin = arrowPs.3
        let isarrowUP = arrowPs.4
        //箭头
        arrowView=UIView(frame: CGRect(x: myFrame.origin.x, y: isarrowUP ? myFrame.origin.y-arrowViewHeight : myFrame.origin.y+myFrame.height, width: myFrame.width, height: arrowViewHeight))
        let layer=CAShapeLayer()
        let path=UIBezierPath()
        path.move(to: arrowPs.0)
        path.addLine(to: arrowPs.1)
        path.addLine(to: arrowPs.2)
        layer.path=path.cgPath
        layer.fillColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.65).cgColor  //绘制曲线的填充色
        arrowView.layer.addSublayer(layer)
       
        
        self.addSubview(arrowView)
        
        tableView=UITableView(frame: CGRect(x: myFrame.origin.x,y: myFrame.origin.y,width: myFrame.width,height: myFrame.height), style: .plain)
        tableView.register(SwiftPopMenuCell.classForCoder(), forCellReuseIdentifier: SwiftPopMenu.cellID)
        tableView.layer.cornerRadius = popMenuCornorRadius
        tableView.separatorStyle = .none
        tableView.layer.masksToBounds = true
        tableView.delegate = self
        tableView.dataSource = self
        tableView.bounces = false
        tableView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.65)
         self.tableView.showsVerticalScrollIndicator = false
        UIView.animate(withDuration: 0.3) {
            self.addSubview(self.tableView)
        }
        self.addSubview(self.tableView)
    }
   
    
    /// 计算箭头位置
    ///
    /// - Returns: (三角箭头顶，三角箭头左，三角箭头右，tableview 原点，是否箭头朝上)
    func getArrowPoints() -> (CGPoint,CGPoint,CGPoint,CGPoint,Bool) {
        if arrowPoint.x <= popMenuMargin {
            arrowPoint.x = popMenuMargin
        }
        if arrowPoint.x >= screenWidth - popMenuMargin{
            arrowPoint.x = screenWidth - popMenuMargin
        }
        var originalPoint = CGPoint.zero
        
        //箭头中间距离左边距离
        var arrowMargin:CGFloat = popMenuMargin
        if arrowPoint.x < screenWidth/2{
            if (arrowPoint.x > myFrame.width/2) {
                arrowMargin = myFrame.width/2
                originalPoint = CGPoint(x: arrowPoint.x - myFrame.width/2, y: arrowPoint.y+arrowViewHeight)
            }else{
                arrowMargin = arrowPoint.x-popMenuMargin
                originalPoint = CGPoint(x: popMenuMargin, y: arrowPoint.y+arrowViewHeight)
            }
            
        }else{
            
            if (screenWidth-arrowPoint.x) < myFrame.width/2{
                arrowMargin = (myFrame.width - screenWidth + arrowPoint.x )
                originalPoint = CGPoint(x: screenWidth-popMenuMargin-myFrame.width, y: arrowPoint.y+arrowViewHeight)
                
                
            }else{
                arrowMargin = myFrame.width/2
                originalPoint = CGPoint(x: arrowPoint.x-myFrame.width/2, y: arrowPoint.y+arrowViewHeight)
            }
        }
        
        //箭头朝上
        if (screenHeight - arrowPoint.y) > myFrame.height{
            
            return (CGPoint(x: arrowMargin, y: 0),CGPoint(x: arrowMargin-arrowViewWidth/2, y: arrowViewHeight),CGPoint(x: arrowMargin+arrowViewWidth/2, y: arrowViewHeight),originalPoint,true)
            
        }else{
            originalPoint.y = arrowPoint.y-myFrame.height-arrowViewHeight
            
            return (CGPoint(x: arrowMargin, y: arrowViewHeight),CGPoint(x: arrowMargin-arrowViewWidth/2, y: 0),CGPoint(x: arrowMargin+arrowViewWidth/2, y: 0),originalPoint,false)
        }
        
    }
    
}



// MARK: - 页面显示、隐藏
extension SwiftPopMenu{
    
    override public func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if touches.first?.view != tableView{
            dismiss()
        }
    }

    public func show() {
        self.stateDelega?.swiftPopMenuState(iShow: true)
        if popData.isEmpty{
            return
        }
        initViews()
        UIApplication.shared.keyWindow?.addSubview(self)
    }
    
    public func dismiss() {
        self.stateDelega?.swiftPopMenuState(iShow: false)
        self.removeFromSuperview()
    }
}

// MARK: - UITableViewDataSource,UITableViewDelegate
extension SwiftPopMenu : UITableViewDataSource,UITableViewDelegate{
    
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return popData.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if popData.count>indexPath.row {
            let cell = tableView.dequeueReusableCell(withIdentifier: SwiftPopMenu.cellID) as! SwiftPopMenuCell
            let model = popData[indexPath.row]
            if indexPath.row == popData.count - 1 {
                cell.fill(title: model, islast: true)
            }else{
                 cell.fill(title: model)
            }
            return cell
        }
        
        return UITableViewCell()
    }
    
    public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return popMenuItemHeight
    }
    
    public func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.01
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        if self.delegate != nil{
            self.delegate?.swiftPopMenuDidSelectIndex(index: indexPath.row)
        }
        if didSelectMenuBlock != nil {
            didSelectMenuBlock!(indexPath.row)
        }
        
        dismiss()
    }
}



/// UITableViewCell
class SwiftPopMenuCell: UITableViewCell {
    var iconImage:UIImageView!
    var lblTitle:UILabel!
    var line:UIView!
    
    //自定义属性
    var lineColor:UIColor = UIColor(red: 80/255.0, green: 81/255.0, blue: 81/255.0, alpha: 0.5)
    var txtColor:UIColor = UIColor.white
    var txtFont:UIFont = UIFont.systemFont(ofSize: 13)
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.backgroundColor = UIColor.clear
        
        lblTitle = UILabel()
        lblTitle.textColor = .white
        lblTitle.textAlignment = .center
        lblTitle.font = .systemFont(ofSize: 14)
        self.contentView.addSubview(lblTitle)
        
        line = UIView()
        line.backgroundColor = UIColor(red: 0.31, green: 0.32, blue: 0.32, alpha: 1)
        self.contentView.addSubview(line)
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func fill(title:String,islast:Bool = false) {
        lblTitle.text = title
        line.isHidden = islast
    }
        
    override func layoutSubviews() {
        super.layoutSubviews()
        self.lblTitle.frame = CGRect(x:self.centerX-(self.bounds.size.width)/2, y: 0, width: self.bounds.size.width, height: self.bounds.size.height)
        self.line.frame = CGRect(x: self.centerX-((75/375)*screenWidth)/2, y: self.frame.size.height - 1, width: (75/375)*screenWidth, height: 1)
    }
}
